package com.prawn.ift_baseconfig.service.impl;

import com.prawn.ift_baseconfig.dao.NetworkTypeDao;
import com.prawn.ift_baseconfig.pojo.Network;
import com.prawn.ift_baseconfig.pojo.NetworkType;
import com.prawn.ift_baseconfig.service.NetworkTypeService;
import entity.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.NullAttributeUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhy
 * @email: 1269679946@qq.com
 * @Date: 2018/10/23
 * @DESC： 网络类型管理服务实现
 */
@Service
public class NetworkTypeServiceImpl implements NetworkTypeService {

    @Autowired
    private NetworkTypeDao networkTypeDao;
    /**
     * 添加网络分类
     * @param networkType
     * @return Result
     */
    @Override
    public Result addNetworkType(NetworkType networkType) {


        NetworkType oldNetworkType =networkTypeDao.findById(networkType.getId()).get();
        BeanUtils.copyProperties(networkType,oldNetworkType, NullAttributeUtils.getNullPropertyNames(networkType));



        networkTypeDao.save(oldNetworkType);
            return Result.success();

    }

    /**
     * 删除网络分类
     * @param id
     * @return Result
     */
    @Override
    public Result deleteNetworkType(String id) {

        networkTypeDao.deleteById(id);
        return Result.success();
    }

    /**
     * 编辑网络分类信息
     * @param networkType
     * @return Result
     */
    @Override
    public Result editNetworkType(NetworkType networkType) {
        if (networkTypeDao.save(networkType) != null) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }

    /**
     * 查询网络分类信息
     * @param id
     * @return NetworkType
     */
    @Override
    public NetworkType getNetworkTypeById(String id) {
        return networkTypeDao.findById(id).get();
    }

    /**
     * 查询网络分类列表
     * @return Result
     */
    @Override
    public Result getNetworkTypeList() {
        Sort sort =  new Sort(Sort.Direction.ASC, "sort");
        List<NetworkType> networkTypeList=networkTypeDao.findAll(sort);

        return Result.success().add(networkTypeList);
    }

    /**
     * 通过父id查询网络分类信息
     * @param parentId
     * @return Result
     */
    @Override
    public Result getNetworkTypeByPid(String parentId) {
        Sort sort=new Sort(Sort.Direction.ASC,"sort");

        Specification<NetworkType> specification=new Specification<NetworkType>() {
            @Override
            public Predicate toPredicate(Root<NetworkType> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 父类编号
                if (parentId!=null && !"".equals(parentId)) {
                    predicateList.add(cb.equal(root.get("parentId").as(String.class), parentId));
                }
                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };

        List<NetworkType> networkTypeList =  networkTypeDao.findAll(specification,sort);

        Result result = new Result();
        result.setData(networkTypeList);
        return result;
    }

    /**
     * 查询网络分类信息，并生成树形数据
     * @return Result
     */
    @Override
    public Result getNetworkTypeTree() {
        //查询所有的分类信息
        List<NetworkType> networkTypeList =(List<NetworkType>) this.getNetworkTypeList().getData();

        //查询顶分类
        List<NetworkType> rootNetworkTypeList =(List<NetworkType>) this.getNetworkTypeByPid("0").getData();

        for (NetworkType networkType : rootNetworkTypeList) {
            networkType.setChildren(getChild(networkType.getId(),networkTypeList));
        }
        Result result = new Result();
        result.setData(rootNetworkTypeList);
        return result;

    }

    /**
     * 递归查询子分类
     * @param id
     * @param networkTypeList
     * @return List<IftEquipmentType>
     */
    private List<NetworkType> getChild(String id, List<NetworkType> networkTypeList) {
        // 子菜单
        List<NetworkType> childList = new ArrayList<>();

        // 遍历所有节点，将父菜单id与传过来的id比较
        for (NetworkType networkType : networkTypeList) {
            if (networkType.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
                if (networkType.getParentId().equals(id)) {
                    childList.add(networkType);
                }
            }
        }

        // 把子菜单的子菜单再循环一遍
        for (NetworkType networkType : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
            // 递归
            networkType.setChildren(getChild(networkType.getId(), networkTypeList));
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<NetworkType> createSpecification(Map searchMap) {

        return new Specification<NetworkType>() {

            @Override
            public Predicate toPredicate(Root<NetworkType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 编号
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                    predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 类型名称
                if (searchMap.get("name")!=null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(cb.like(root.get("name").as(String.class), "%"+(String)searchMap.get("name")+"%"));
                }
                // 父类编号
                if (searchMap.get("parentId")!=null && !"".equals(searchMap.get("parentId"))) {
                    predicateList.add(cb.like(root.get("parentId").as(String.class), "%"+(String)searchMap.get("parentId")+"%"));
                }
                //  多层父id串
                if (searchMap.get("parentIds")!=null && !"".equals(searchMap.get("parentIds"))) {
                    predicateList.add(cb.like(root.get("parentIds").as(String.class), "%"+(String)searchMap.get("parentIds")+"%"));
                }
                // 备注信息
                if (searchMap.get("remarks")!=null && !"".equals(searchMap.get("remarks"))) {
                    predicateList.add(cb.like(root.get("remarks").as(String.class), "%"+(String)searchMap.get("remarks")+"%"));
                }
                // 创建者
                if (searchMap.get("createBy")!=null && !"".equals(searchMap.get("createBy"))) {
                    predicateList.add(cb.like(root.get("createBy").as(String.class), "%"+(String)searchMap.get("createBy")+"%"));
                }
                // 更新者
                if (searchMap.get("updateBy")!=null && !"".equals(searchMap.get("updateBy"))) {
                    predicateList.add(cb.like(root.get("updateBy").as(String.class), "%"+(String)searchMap.get("updateBy")+"%"));
                }
                // 删除标记
                if (searchMap.get("delFlag")!=null && !"".equals(searchMap.get("delFlag"))) {
                    predicateList.add(cb.like(root.get("delFlag").as(String.class), "%"+(String)searchMap.get("delFlag")+"%"));
                }

                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }

}
